package com.dlc.shop.seckill.common.listener;

import com.dlc.shop.bean.enums.ProdStatusEnums;
import com.dlc.shop.bean.enums.ProdType;
import com.dlc.shop.bean.event.ProdChangeStatusEvent;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.bean.order.GeneralActivitiesOrder;
import com.dlc.shop.seckill.common.model.Seckill;
import com.dlc.shop.seckill.common.service.SeckillService;
import com.dlc.shop.seckill.common.service.SeckillSkuService;
import com.dlc.shop.service.ProductService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 秒杀商品状态修改监听
 * @author LGH
 */
@Component("seckillProdChangeStatus")
@AllArgsConstructor
public class ProdChangeStatusListener {
    private final SeckillService seckillService;

    private final ProductService productService;

    private final SeckillSkuService seckillSkuService;

    /**
     * 使秒杀活动失效
     */
    @EventListener(ProdChangeStatusEvent.class)
    @Order(GeneralActivitiesOrder.SECKILL)
    public void seckillProdChangeStatusListener(ProdChangeStatusEvent event) {
        Product product = event.getProduct();
        // 不是秒杀商品，就不用管他
        if(!Objects.equals(product.getProdType(), ProdType.PROD_TYPE_SECKILL.value())){
            return;
        }

        // 如果是商品上线，就不管他了
        if (Objects.equals(ProdStatusEnums.NORMAL.getValue(), event.getStatus())) {
            return;
        }

        // 平台审核
        if (Objects.equals(ProdStatusEnums.PLATFORM_AUDIT.getValue(), event.getStatus())) {
            return;
        }

        Seckill seckill = seckillService.getById(product.getActivityId());

        seckillService.invalidById(seckill);
        seckillSkuService.handSeckillPointSku(seckill);

        productService.removeProdCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
    }
}
